package com.weijun.keepalive.service

import android.app.job.JobInfo
import android.app.job.JobParameters
import android.app.job.JobScheduler
import android.app.job.JobService
import android.content.ComponentName
import android.content.Intent
import android.os.Build.VERSION
import com.weijun.keepalive.CLICK_NOTIFICATION
import com.weijun.keepalive.LOCAL_SERVICE_NAME
import com.weijun.keepalive.NOTIFY_LEVEL
import com.weijun.keepalive.isRunningTaskExist
import com.weijun.keepalive.isServiceRunning
import com.weijun.keepalive.logE
import com.weijun.keepalive.receiver.NotificationClickReceiver
import com.weijun.keepalive.utils.createNotification

/**
 * @author: weijun
 * date: 2023/7/6
 * description:JobService:https://blog.csdn.net/qq_38350635/article/details/106390343
 */
class JobHandlerService : JobService() {

    companion object {
        private const val JOB_ID = 100
    }

    private val mJobScheduler by lazy(LazyThreadSafetyMode.NONE) { getSystemService(JOB_SCHEDULER_SERVICE) as JobScheduler }

    override fun onStartJob(params: JobParameters?): Boolean {
        "JobHandlerService onStartJob".logE()
        if (!applicationContext.isServiceRunning(LOCAL_SERVICE_NAME) || !applicationContext.isRunningTaskExist("$packageName:remote")) {
            startService()
        }
        return false
    }

    override fun onStopJob(params: JobParameters?): Boolean {
        "JobHandlerService onStopJob".logE()
        if (!applicationContext.isServiceRunning(LOCAL_SERVICE_NAME) || !applicationContext.isRunningTaskExist("$packageName:remote")) {
            startService()
        }
        return false
    }

    private fun startService() {
        if (VERSION.SDK_INT >= 26) {
            startForeground(NOTIFY_LEVEL, createNotification(Intent(this.applicationContext, NotificationClickReceiver::class.java).apply {
                action = CLICK_NOTIFICATION
            }))
        }
        startService(Intent(this, LocalService::class.java))
        startService(Intent(this, RemoteService::class.java))
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        "JobHandlerService onStartCommand".logE()
        startService()
        mJobScheduler.cancel(JOB_ID)
        val builder = JobInfo.Builder(JOB_ID, ComponentName(packageName, JobHandlerService::class.java.name))
        if (VERSION.SDK_INT >= 24) {
            builder.setMinimumLatency(30 * 1000) //特定条件限制：延迟30秒后开启
            builder.setOverrideDeadline(30 * 1000)//设置执行的最后期限，在最后期限到达之前会执行此job（与setPeriodic一起使用会报异常）
            builder.setBackoffCriteria(30 * 1000, JobInfo.BACKOFF_POLICY_LINEAR)//设置重新调度Job的策略
        } else {
            builder.setPeriodic(30 * 1000) //设置的时间段内执行，执行不会超过一次。你不能控制执行的时间，仅仅能确定的是在设定的期间内job会执行一次。（安卓7.0开始这个值最小要设置15min否则15min内不起作用）
        }
        builder.setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY)//特定条件限制：任意网络
        builder.setPersisted(true) //设备重启后是否继续后台操作
        mJobScheduler.schedule(builder.build())
        return START_STICKY
    }
}